package tool

import (
	"errors"
	p "fhst/templates"
	"fhst/utils"
	"fmt"
	"strings"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

// 添加线程安全的map缓存
func AddJWT() error {
	defer func() {
		info := utils.History{
			Name:   "开启JWT",
			Op:     "添加jwt token支持",
			Common: "fhst tool jwt",
		}
		_, err := utils.AddHistory(&info)
		if err != nil {
			log.Error(err)
		}
	}()

	// 数据库初始化
	utils.ConnectInit()

	// 判断当前位置是否有utils文件夹
	if !utils.IsPathExists(".fhst") {
		return errors.New("未发现.fhst文件，请回到项目根目录")
	}

	if utils.IsPathExists("core/middlewares/jwt.go") {
		return errors.New("jwt.go已经存在")
	}

	rs, err := utils.ReadFile(".fhst")
	if err != nil {
		return err
	}

	pkgname := strings.Split(string(rs), ":")
	data := map[string]interface{}{
		"Pkg":     pkgname[1],
		"Name":    pkgname[0],
		"Apps":    viper.GetStringSlice("app"),
		"Swagger": viper.GetBool("swagger"),
		"Jwt":     true,
		"Admin":   viper.GetBool("admin"),
	}

	// 写入配置文件
	defer func() {
		viper.Set("jwt", true)
		viper.WriteConfigAs(fmt.Sprintf("%s.yaml", pkgname[0]))
	}()

	// 创建common通用文件
	log.Infof("初始化jwt模板")
	err = utils.WriteFileByTemplate(p.Middlewares, "middlewares/jwt.tmpl", "core/middlewares/jwt.go", data)
	if err != nil {
		return err
	}

	log.Infof("初始化jwt controller模板")
	err = utils.WriteFileByTemplate(p.Middlewares, "middlewares/jwtcontroller.tmpl", "core/middlewares/jwtcontroller.go", data)
	if err != nil {
		return err
	}

	log.Infof("注册auth路由表")
	err = utils.WriteFileByTemplate(p.Project, "project/register.tmpl", "core/router/register.go", data)
	if err != nil {
		return err
	}
	return nil
}
